package com.ldn.common.basic.utils.system;

import cn.hutool.core.date.DateUnit;
import cn.hutool.cron.CronUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * CronUtils类继承并扩展了hutool CronUtil
 *
 * @author 李大牛家的牛 (scafel@163.com)
 * @product serverless
 * @className CronUtils
 * @createDate 2025/1/17 - 16:43
 * @description CronUtils类继承并扩展了hutool CronUtil
 **/
@Slf4j
public class CronUtils extends CronUtil {

    private static final Map<String, String> cronMap = new ConcurrentHashMap<>();

    /**
     * 动态设置定时任务
     *
     * @param msg       任务描述
     * @param cronId    任务id
     * @param time      任务时间
     * @param after     任务执行后
     */
    public static void setCronTask(String msg, String cronId,long time, Function<Void, Void> after) {
        if (cronMap.containsKey(cronId)){
            return;
        }
        if (DateUtils.getNumberForNow(time, DateUnit.SECOND) <= 0){
            after.apply(null);
            return ;
        }
        cronMap.put(cronId, cronId);
        schedule(cronId, DateUtils.onlyOnceCron(time), () -> {
            log.info("定时任务，开始执行" + DateUtils.formatDate(time) + "-" + msg);
            try {
                after.apply(null);
                remove(cronId);
                cronMap.remove(cronId);
            }catch (Exception e){
                log.error("定时任务，执行失败", e);
            }
        });
    }


    /**
     * 移除定时任务
     *
     * @param cronId 任务id
     */
    public static void removeCronTask(String cronId) {
        remove(cronId);
        cronMap.remove(cronId);
    }
}
